__author__ = 'l4537'
#coding:utf-8
import telnetlib,time,re,sys
#进度条
def view_bar(num,total):
    ret = num / total
    ag = int(ret * 100)
    ab = "\r [%-100s]%d%%" %( '='*num,ag, )
    sys.stdout.write(ab)
    sys.stdout.flush()
def Telnet(ip,user,password,commands):
    try:
        tn = telnetlib.Telnet(ip)
    except Exception as e:
        print("IP 地址连接错误")
        Errlog(ip,e,"地址连接错误,无法连接")
        Startsan()
    tn.read_until(b"login:",timeout=5)
    tn.write(user.encode('ascii') + b"\n")
    if password:
        tn.read_until(b"Password: ",timeout=5)
        tn.write(password.encode('ascii') + b"\n")
    tn.read_some()
    result = tn.read_some()
    rex = r'incorrect'
    tmp = re.search(rex,str(result))
    if not tmp == None:
        print("密码错误")
        Errlog(ip,"账户或者密码错误")
        Startsan()
    for k in range(6):
        tn.write(b"\n")
    b = 0
    for i in commands:
        comm = i + "\n"
        b +=1
        time.sleep(3)
        view_bar(b,len(commands))
        tn.write(str.encode(comm))
    for k in range(20):
        tn.write(b"\n")
    tn.write(b"exit\n")
    data = tn.read_all().decode('utf-8')
    #print (data)
    Log(ip,data)
def Log(ip,data):
    name = str(ip +'-'+ time.strftime('%Y%m%d%H%M') + '.txt')
    file_name = open(name,mode='a')
    file_name.write(data.encode("utf-8"))
    file_name.close()
def Errlog(ip,errmessages):
    time_log = time.strftime('%Y-%m-%d %H:%M:%S')
    err_log = open('messages.log',mode='a')
    err_log.write(time_log + '   '+ ip +"   "+ errmessages + "\n")
    err_log.close()
def Startsan():
    command = ["slotshow","chassisshow","switchshow","zoneshow","hashow","porterrshow","fanshow","firmwareshow",'version','licenseshow ','uptime','date','fabricshow','memshow',"psshow","exit"]
    ip = str(input("请输入IP地址:"))
    Telnet(ip,"admin","Jxyd@Bc0791san",command)
Startsan()